package zyh.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(filterName = "authority",urlPatterns = {"/*"},initParams = {
//        @WebInitParam(name = "encoding",value = "utf-8"),
//        @WebInitParam(name = "LoginServlet",value = "/login"),
//        @WebInitParam(name = "shop",value = "/shop.jsp")
//})
//@WebFilter(filterName = "authority",urlPatterns = {"/*"})
public class AuthorityFilter implements Filter{
    private FilterConfig config;
    public void init(FilterConfig config) throws ServletException {
        this.config=config;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        String encoding=config.getInitParameter("encoding");
//        String loginPage=config.getInitParameter("LoginServlet");
//        String shopping=config.getInitParameter("shop");
//        request.setCharacterEncoding(encoding);
        HttpServletRequest requ=(HttpServletRequest)request;
        HttpSession session=requ.getSession(true);
        String requestPath=requ.getServletPath();
        if("/login".equals(requestPath))
        {
            chain.doFilter(request, response);
        }
        else if (session.getAttribute("user") == null)
//                && !requestPath.endsWith(loginPage) && !requestPath.endsWith(shopping)
            {
//            request.setAttribute("tip" ,"您还没有登录");
                request.getRequestDispatcher("/login").forward(request, response);
            } else {
                chain.doFilter(request, response);
            }

    }

    public void destroy() {
        this.config=null;
    }
}
